<template>
  <div>
    <el-button
      type="primary"
      class="mt-2"
      :loading="uploading"
      :disabled="disabled"
      @click="triggerFile"
    >
      上传
    </el-button>
    <input
      ref="fileInput"
      type="file"
      :accept="accept"
      :multiple="true"
      style="display: none"
      @change="handleFiles"
      :disabled="disabled"
    />
    <el-progress
      v-if="uploading"
      :percentage="100"
      :indeterminate="true"
      status="success"
      class="mt-2"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { uploadFile } from '@/api/api.js'

const props = defineProps({
  accept: { type: String, default: '' },
  disabled: { type: Boolean, default: false }
})

const emit = defineEmits(['success'])

const fileInput = ref(null)
const uploading = ref(false)

function triggerFile() {
  fileInput.value && fileInput.value.click()
}

async function handleFiles(e) {
  const files = Array.from(e.target.files)
  if (!files.length) return
  uploading.value = true
  try {
    const results = []
    for (const file of files) {
      const fd = new FormData()
      fd.append('file', file)
      const res = await uploadFile(fd)
      results.push(res.data || res.Data || res)
    }
    emit('success', results)
  } catch (e) {
	console.error('上传失败:', e.message );
    alert('上传失败')
  } finally {
    uploading.value = false
    // 清空 input，否则无法连续上传同一个文件
    e.target.value = ''
  }
}
</script>